<template>
  <form-item-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :sub-form-row-id="subFormRowId"
  >
    <el-row justify="space-between" v-if="!isReadMode">
      <el-col :span="22">
        <el-input
          ref="fieldEditor"
          v-if="!isReadMode"
          v-model="field.options.defaultValue"
          readonly
          :disabled="field.options.readonly || field.options?.isAllowEditSelectorField == '2'"
          :placeholder="field.options.placeholder"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button
          v-if="seniorDetail?.breakNumber == '1'"
          type="primary"
          size="small"
          plain
          :icon="Tickets"
          :disabled="!!formInfo.currentTodoId"
          @click.stop="handleOpenDialog"
        />
      </el-col>
    </el-row>

    <template v-if="isReadMode">
      <span class="readonly-mode-field">{{ field.options.defaultValue }}</span>
    </template>

    <serial-broken
      ref="serialBrokenRef"
      :title="title"
      @confirm="confirmSerial"
    ></serial-broken>
  </form-item-wrapper>
</template>

<script>
import { Tickets } from "@element-plus/icons-vue"
import FormItemWrapper from "./form-item-wrapper"
import emitter from "@/utils/emitter"
import i18n, { translate } from "@/utils/i18n"
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin"
import {
  bindSerialNumAPI,
  getSerialNumByFormIdAPI,
  getDetailSenior,
  getBreakNumber,
  getSerialRuleByFormIdAPI,
} from "@/api/document/serial"
import { generateId } from "@/utils/util"
import serialBroken from "@/components/ZHLX-Components/ZHLX-serialBroken/index.vue"

export default {
  name: "serial-number-widget",
  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
  },
  inject: ["getGlobalDsv"],
  components: {
    FormItemWrapper,
    serialBroken,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],
      title: "选择断号",
      widgetKey: "",
      isRefresh: false,
      formInfo: this.getGlobalDsv()["flowDetailForm"],
      ruleInfo: {},
      seniorDetail: {},
      Tickets,
    }
  },
  computed: {
    allowDefaultFirstOption() {
      return !!this.field.options.filterable || !!this.field.options.remote
    },

    remoteMethod() {
      if (!!this.field.options.remote && !!this.field.options.onRemoteQuery) {
        return this.remoteQuery
      } else {
        return undefined
      }
    },

    selectKey() {
      return this.widgetKey || this.field.id
    },
  },
  watch: {
    isRefresh: {
      handler() {
        this.generateSerialNum()
      },
    },
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  async created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
         需要在父组件created中初始化！！ */
    this.registerToRefList()
    this.initFieldModel()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()
    await this.getBindRules()
    await this.getSeniorDetailInfo()
  },

  mounted() {
    this.handleOnMounted()
    // if (this.field.options.defaultValue) {
    //   this.getSerialNumByFormId()
    // }
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {
    async generateSerialNum() {
      if (this.designState) return
      if (!this.field.options.readonly) {
        // 编辑
        if (!this.field.options.defaultValue) {
          if (this.field.options.bindSerialNum) {
            // 根据绑定流水号规则请求接口获取流水号
            await this.bindSerialNum()
            // this.getSerialNumByFormId()
          }else {            
            await this.bindSerialNumHanlder()
          } 
          
        }
      }
    },
    /**
     * 获取选中项label
     * @return {*}
     */
    getSelectedLabel() {
      return this.$refs.fieldEditor.selectedLabel
    },
    async getBindRules() {
      await getSerialRuleByFormIdAPI({
        formId: this.formInfo.formId,
      }).then(res => {
        this.ruleInfo = res.data
      })
    },
    /**
     * 打开弹窗
     */
    async handleOpenDialog() {
      if (this.field.options.readonly || this.isReadMode) return
      let params = {} 
      if (this.field.options.bindSerialNum) {
        params = {
          turnoverCode: this.field.options.bindSerialNum,
          exampleId: this.formInfo.exampleId || '',
        }      
      }else {
        params = {
          turnoverCode: this.ruleInfo.turnoverCode,
          exampleId: this.formInfo.exampleId || '',
        }
      }
      const res = await getDetailSenior(params)
      if (res.data.breakNumber == "1") {
        const broken = await getBreakNumber({
          flowingWaterId: res.data.id,
          bingFrom: this.formInfo.formId,
        })
        if (broken.data.length == 0) {
          this.$message.warning("暂无断号，系统将自动生成断号")
          return
        }
        this.$refs.serialBrokenRef.init(broken.data)
      }
    },

    async getSeniorDetailInfo() {
      let params = {}
      if (this.field.options.bindSerialNum) {
        params = {
          turnoverCode: this.field.options.bindSerialNum,
          exampleId: this.formInfo.exampleId || '',
        }      
      }else {
        params = {
          turnoverCode: this.ruleInfo.turnoverCode,
          exampleId: this.formInfo.exampleId || '',
        }
      }
      const res = await getDetailSenior(params)
      if(res.code == 0) {
        this.seniorDetail = res.data
      }
      console.log("this.seniorDetail==== 有bindSerialNumber", this.seniorDetail)
    },

    refreshWidgetKey() {
      //强制刷新组件！！
      this.widgetKey = "select-key-" + generateId()
    },
    /**
     * 绑定流水号
     */
    async bindSerialNum() {
      // 编辑权限 并且有绑定流水号规则.
      if (!this.field.options.readonly && this.field.options.bindSerialNum) {
        bindSerialNumAPI({
          id: this.field.options.bindSerialNum, // 流水号id规则
          formId: this.formInfo.formId, // 文单id
          formName: this.formInfo.formName || this.formInfo.formJson.formName, // 文单名称
          // 使用 || 判断没值时，默认为简单模式 0， 对历史数据进行处理
          modelType: this.field.options.bindSerialModelType || '0', // 流水号规则类型
        })
          .then((res) => {
            if (res.ok) {
              // this.$message.success(res.msg)
            }
          })
          .catch((err) => {
            if(!this.formInfo.exampleId) {
              this.$message.error(err.msg || "绑定流水号失败")
            }
            // this.$message.error(err.msg || "绑定流水号失败")
          })
      }
    },
    async bindSerialNumHanlder() {
      if (!this.field.options.readonly) {
        const res = await getSerialRuleByFormIdAPI({
          formId: this.formInfo.formId,
        })
        if (res.data) {
          bindSerialNumAPI({
            id: res.data.turnoverCode, // 流水号id规则
            formId: res.data.bingFrom, // 文单id
            formName: res.data.formName, // 文单名称
            // 默认为简单模式 '0'， 兼容历史数据进行处理
            modelType: res.data.modelType || '0', // 流水号规则类型
          })
            .then((res) => {
              if (res.ok) {
                // this.$message.success(res.msg)
              }
            })
            .catch((err) => {
              if(!this.formInfo.exampleId) {
                this.$message.error(err.msg || "绑定流水号失败")
              }
            })
        }
      }
    },
    /**
     * 获取表单绑定的流水号
     */
    getSerialNumByFormId() {
      if (!this.formInfo || !this.formInfo.formId) {
        return
      }
      getSerialNumByFormIdAPI(this.formInfo.formId)
        .then((res) => {
          if (res.ok && res.data) {
            this.field.options.defaultValue = res.data
            this.syncUpdateFormModel(res.data)
          }
        })
        .catch((err) => {
          // this.$message.error(err.msg || "获取流水号失败")
        })
    },
    confirmSerial(selectedSerial) {
      this.field.options.defaultValue = selectedSerial.serial
      this.getGlobalDsv().serialBrokenId(selectedSerial)
    },
  },
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/global.scss"; /* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}
</style>
